home *** CD-ROM | disk | FTP | other *** search
- Path: news.primenet.com!jstern
- From: jstern@primenet.com (Josh Stern)
- Newsgroups: comp.lang.c++
- Subject: Re: what getline returns? Nobody can explain this!!
- Date: 18 Mar 1996 18:11:01 -0700
- Organization: Primenet Services for the Internet
- Sender: root@primenet.com
- Distribution: na
- Message-ID: <4il1j5$525@nnrp1.news.primenet.com>
- References: <4ifbk8$6nf@bcarh8ab.bnr.ca>
- X-Posted-By: jstern@usr3.primenet.com
-
- In article <4ifbk8$6nf@bcarh8ab.bnr.ca>, whyme <liyu@bnr.ca> wrote:
- >getline member fuction in ifstream is supposed to return the
- >receiving object (that is, ostream&).
- >
- >However, many books contain the code samples like:
- >
- >ifstream in("tmp.txt");
- >while (in.getline(buffer,sizeof(buffer))) { ... }
- >
- >This loop quits only if in.getline returns 0 or NUll;
- > ^^^^^^^
- >
- >but an ostream object is neither 0 nor NULL;
- >the result is an object, not integer or pointer.
- >
- >So how can this loop quit?
- >
- >It works; but no one I know can explain this!!!!
- >Thanks for your help.
-
- It works because ostream or one of the base classes that
- it inherits from has defined a type conversion to a
- type that can be logically tested in this manner, and
- thus supports the type of useful and familiar idiom
- that you described. Here is a relevant portion of
- the g++ implementation of class ios, that is a
- base class for the iostreams:
-
- int fail() const { return _state & (ios::badbit|ios::failbit); }
- int bad() const { return _state & ios::badbit; }
- iostate rdstate() const { return _state; }
- operator void*() const { return fail() ? (void*)0 : (void*)(-1); }
- int operator!() const { return fail(); }
-
- So any code that would work with a FILE* variable by
- testing whether the pointer is NULL, would work with ios and
- descendants, since the compiler would invoke the type conversion
- to void* (assuming no further overloading).
-
- - Josh
-
-
- --
- -------------------------------------------------------------------------------
- jstern
- jstern@primenet.com
- -------------------------------------------------------------------------------
-